import Vue from "vue";
import Router from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import VueCookies from "vue-cookies";
import store from "./store";

import Login from "./pages/system/Login.vue";
import MiddleRouter from "./pages/system/MiddleRouter.vue";
import NotFoundView from "./pages/frame/NotFound";
import Frame from "./pages/frame/Frame";
import Home from "./pages/system/Home";
import UserManager from "./pages/system/UserManager";
import SystemRouter from "./pages/system/SystemRouter";
import CarManager from "./pages/system/CarManager";
import UserCarManager from "./pages/system/UserCarManager";

Vue.use(Router);

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return {
        x: 0,
        y: 0
      };
    }
  },
  routes: [
    {
      path: "/",
      redirect: "/login"
    },
    {
      path: "/login",
      component: Login
    },
    {
      path: "",
      component: Frame,
      meta: { auth: true, keepAlive: true },
      children: [
        {
          path: "/home",
          component: Home,
          name: "home",
          meta: {
            keepAlive: true
          }
        },
        //  路由跳转的中间组件
        {
          path: "/middle-router",
          component: MiddleRouter,
          name: "middle-router"
        },
        {
          path: "/system",
          component: SystemRouter,
          name: "system",
          children: []
        },
        {
          path: "/userManager",
          component: UserManager
        },
        {
          path: "/carManager",
          component: CarManager
        },
        {
          path:"/userCarManager",
          component:UserCarManager
        }
      ]
    },
    { path: "*", component: NotFoundView }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.path !== from.path) {
    NProgress.start();
  }
  if (to.matched.some(record => record.meta.auth)) {
    if (!isLogin()) {
      next({
        path: "/login"
      });
    }
    NProgress.done();
  }

  next();
});

/**
 * 重写路由的push方法
 */
const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};

router.afterEach(() => {
  NProgress.done();
});

function isLogin() {
  if (!store.getters.userInfo || store.getters.userInfo === {}) {
    //看看cookie是否有信息
    let userInfo = VueCookies.get("userInfo");
    if (userInfo) {
      store.dispatch("userStore/setUserInfo", userInfo);
      return true;
    }
    return false;
  }
  return true;
}

export default router;
